package com.watt.gateway.interceptor;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.watt.gateway.domain.FailResultEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;

@Component
public class CustomZuulPostFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(CustomZuulPostFilter.class);

    @Override
    public String filterType() {
        //后置过滤器
        return "post";
    }

    @Override
    public int filterOrder() {
        //优先级，数字越大，优先级越低
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //是否执行该过滤器，true代表需要过滤
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        log.info("进入post过滤器");
        System.out.println(ctx.getResponseBody());
        HttpServletResponse req = ctx.getResponse();
        System.out.println("status ---->:" + req.getStatus());
        if (req.getStatus() >= 500) {
            FailResultEntity info = new FailResultEntity("业务服务异常");
            ctx.setResponseBody(JSON.toJSONString(info));
        }
        return null;
    }
}

